💯 solving-algo | February 14, 2021
banned
단어를 제외한 가장 긴 단어를 찾는 문제
https://leetcode.com/problems/most-common-word/
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words = [word for word in re.sub(r'[^\w]', ' ', paragraph)
.lower().split()
if word not in banned]
counts = collections.Counter(words)
return counts.most_common(1)[0][0]
가장 빠른 연산 처리를 위해 정규 표현식 방법으로 [^\w]
를 썻으며, ^
는 Not을 의미, \w
는 단어와 문자를 의미한다.
즉, 단어와 문자가 아닌 것들은 모두 공백처리를 통해 쉽게 구분할 수 있었고, banned
변수에 들어있는 문자 또한 조건문 처리로 쉽게 해결할 수 있었다.